//在vue项目中使用长连接获取动态消息

import { getToken } from '@/utils/auth'
import { getUserInfo } from '@/api/login'

import router from '../router/index'

import { Notification } from 'element-ui'

// 长连接配置
const webSock = {
  // 设置长连接地址
  setWebSockUrl() {
    const URL = process.env.BASE_API
    console.log('长连接Api地址', URL)
    const arr = URL.split('//')
    console.log('长连接域名', arr[1])
    const finallyURL = arr[1].split('/')[0]
    console.log('finallyURL=', finallyURL)
    return finallyURL
  },
  // 初始化webSock
  initWebSocket() {
    const wsURL = 'ws://' + this.setWebSockUrl() + ':20002'// ws地址
    console.log('wsURL=', wsURL)
    this.websock = new WebSocket(wsURL)

    this.websock.onopen = webSockTonOpen

    this.websock.onerror = webSockTonError

    this.websock.onmessage = webSockToMessage

    this.websock.onclose = webSockToClose
  }
}
// 链接
function webSockTonOpen() {
  console.log('WebSocket连接成功')
  setInterval(() => { // 没10秒发送一次验证链接通畅
    const data = JSON.stringify({ type: 'ping' })
    this.send(data)
  }, 10000)
  // 获取shop_id
  getUserInfo().then(res => {
    const userData = res.data
    if (userData.status_code === 200) {
      // 登录
      const data = JSON.stringify({ type: 'login', data: { shop_id: userData.data.shop_id, token: getToken() }})
      this.send(data)
    }
  })
}
// 错误
function webSockTonError(e) { // 错误
  console.log('WebSocket连接发生错误->', unescape(JSON.parse(e.data).message))
}
// 消息
function webSockToMessage(e) { // 数据接收
  // 注意：长连接我们是后台直接1秒推送一条数据，
  // 但是点击某个列表时，会发送给后台一个标识，后台根据此标识返回相对应的数据，
  // 这个时候数据就只能从一个出口出，所以让后台加了一个键，例如键为1时，是每隔1秒推送的数据，为2时是发送标识后再推送的数据，以作区分
  const data = JSON.parse(e.data)
  if (data.type === 'new_order') { // 新订单
    messageAlert({ type: 'new_order', option: data.result })
  } else if (data.type === 'financial_audit') { // 待审核订单
    messageAlert({ type: 'financial_audit', option: data.result })
  } else if (data.type === 'store_audit') { // 待出库订单
    messageAlert({ type: 'store_audit', option: data.result })
  } else if (data.type === 'new_refund_order') { // 新退货单
    messageAlert({ type: 'new_refund_order', option: data.result })
  } else if (data.type === 'refund_store_audit') { // 退款单待收货确认
    messageAlert({ type: 'refund_store_audit', option: data.result })
  } else if (data.type === 'refund_financial_audit') { // 退款单待退款确认
    messageAlert({ type: 'refund_financial_audit', option: data.result })
  } else if (data.type === 'pay_order') { // 订单付款
    messageAlert({ type: 'pay_order', option: data.result })
  } else if (data.type === 'user_recharge') { // 充值
    messageAlert({ type: 'user_recharge', option: data.result })
  } else if (data.type === 'put_store') { // 出库
    messageAlert({ type: 'put_store', option: data.result })
  } else if (data.type === 'set_store') { // 入库
    messageAlert({ type: 'set_store', option: data.result })
  } else if (data.type === 'timeout') {
    webSock.initWebSocket()
  }
}

// 数据发送
function webSockToSend(agentData) { // 数据发送
  console.log('数据发送=', agentData)
  const data = JSON.stringify(agentData)
  webSock.websock.send(data)
}
// 关闭
function webSockToClose(e) { // 关闭
  console.log(`长连接关闭 (${e.code})`)
}
// -----------------信息来往交互-----------------
// 设置不同样式的消息
function setHtmlContent(type, message) {
  let color = ''
  if (type === 'new_order') { // 新订单
    color = '#95c23e'
  } else if (type === 'financial_audit') { // 待审核订单
    color = '#e5ca49'
  } else if (type === 'store_audit') { // 待出库订单
    color = '#E5CF44'
  } else if (type === 'new_refund_order') { // 新退货单
    color = '#7ED1D0'
  } else if (type === 'refund_store_audit') { // 退款单待收货确认
    color = '#89A5EF'
  } else if (type === 'refund_financial_audit') { // 退款单待退款确认
    color = '#89A5EF'
  } else if (type === 'pay_order') { // 订单付款
    color = '#EC6054'
  } else if (type === 'user_recharge') { // 充值
    color = '#EC6054'
  } else if (type === 'put_store') { // 出库
    color = '#68B1E2'
  } else if (type === 'set_store') { // 入库
    color = '#386DB0'
  }
  const span = '<span ' +
  'style="' +
  'display: inline-block;' +
  'width: 10px;' +
  'height:100%;' +
  'position: absolute;' +
  'left: 0;top: 0;background-color: ' + color + ';"></span>'
  return '<p style="cursor: pointer;color: #409EFF;font-size: 14px;text-decoration: underline">' + span + message + '</p>'
}
// 设置弹出消息
function messageAlert(data) {
  const options = {
    title: '',
    position: 'bottom-right',
    dangerouslyUseHTMLString: true,
    duration: 3000,
    message: '',
    onClick: () => {}
  }
  if (data.type === 'new_order') { // 新订单
    options.title = '新订单'
    options.message = setHtmlContent('new_order', data.option.message)
    options.onClick = () => {
      webSockToSend({ type: 'notice_read', data: { nid: data.option.nid }})
      router.push({ name: 'order-detail', query: {
        id: data.option.data.order_id,
        type: 'detail'
      }})
    }
  } else if (data.type === 'financial_audit') { // 待审核订单
    options.title = '待审核订单'
    options.message = setHtmlContent('financial_audit', data.option.message)
    options.onClick = () => {
      webSockToSend({ type: 'notice_read', data: { nid: data.option.nid }})
      router.push({ name: 'order-detail', query: {
        id: data.option.data.order_id,
        type: 1
      }})
    }
  } else if (data.type === 'store_audit') { // 待出库订单
    options.title = '待出库订单'
    options.message = setHtmlContent('store_audit', data.option.message)
    options.onClick = () => {
      webSockToSend({ type: 'notice_read', data: { nid: data.option.nid }})
      router.push({ name: 'order-detail', query: {
        id: data.option.data.order_id,
        type: 2
      }})
    }
  } else if (data.type === 'new_refund_order') { // 新退货单
    options.title = '新退货单'
    options.message = setHtmlContent('new_refund_order', data.option.message)
    options.onClick = () => {
      webSockToSend({ type: 'notice_read', data: { nid: data.option.nid }})
      router.push({ name: 'refunds-detail', query: {
        id: data.option.data.order_refund_id,
        type: 'detail'
      }})
    }
  } else if (data.type === 'refund_store_audit') { // 退款单待收货确认
    options.title = '退款单待收货确认'
    options.message = setHtmlContent('refund_store_audit', data.option.message)
    options.onClick = () => {
      webSockToSend({ type: 'notice_read', data: { nid: data.option.nid }})
      router.push({ name: 'refunds-detail', query: {
        id: data.option.data.order_refund_id,
        type: 1
      }})
    }
  } else if (data.type === 'refund_financial_audit') { // 退款单待退款确认
    options.title = '退款单待退款确认'
    options.message = setHtmlContent('refund_financial_audit', data.option.message)
    options.onClick = () => {
      webSockToSend({ type: 'notice_read', data: { nid: data.option.nid }})
      router.push({ name: 'refunds-detail', query: {
        id: data.option.data.order_refund_id,
        type: 2
      }})
    }
  } else if (data.type === 'pay_order') { // 订单付款
    options.title = '订单付款'
    options.message = setHtmlContent('pay_order', data.option.message)
    options.onClick = () => {
      webSockToSend({ type: 'notice_read', data: { nid: data.option.nid }})
      router.push({ name: 'order-detail', query: {
        id: data.option.data.order_id,
        type: 'detail'
      }})
    }
  } else if (data.type === 'user_recharge') { // 充值
    options.title = '账户充值'
    options.message = setHtmlContent('user_recharge', data.option.message)
    options.onClick = () => {
      webSockToSend({ type: 'notice_read', data: { nid: data.option.nid }})
      router.push({ name: 'gather-confirm', query: {
        id: data.option.data.order_gathering_id
      }})
    }
  } else if (data.type === 'set_store') { // 入库
    options.title = '新入库'
    options.message = setHtmlContent('user_recharge', data.option.message)
    options.onClick = () => {
      webSockToSend({ type: 'notice_read', data: { nid: data.option.nid }})
      router.push({ name: 'put-storage-detail', query: {
        id: data.option.data.store_doc_id,
        type: 'detail'
      }})
    }
  } else if (data.type === 'put_store') { // 出库
    options.title = '新出库'
    options.message = setHtmlContent('user_recharge', data.option.message)
    options.onClick = () => {
      webSockToSend({ type: 'notice_read', data: { nid: data.option.nid }})
      let id
      if (data.option.data.type === 5) { // 订单出库
        id = data.option.data.order_id
        router.push({ name: 'order-detail', query: {
          id: id,
          type: 2
        }})
      } else { // 新增出库单出库
        id = data.option.data.store_doc_id
        router.push({ name: 'deliver-storage-detail', query: {
          id: id,
          type: 'detail'
        }})
      }
    }
  } else {
    console.log('error')
  }
  Notification(options)
}

export default webSock
